<?php

namespace App\Models\V1;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Tymon\JWTAuth\Contracts\JWTSubject;

class Admins extends Authenticatable  implements  JWTSubject
{
    use Notifiable;

    protected $table="sys_admins";
    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'username',
        'password',
        'mobile',
        'nickname',
        'avatar',
        'email',
        'qq',
        'sex',
        'token',
        'is_google_auth',
        'google_secret',
        'state',
        'remark'
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'token',
    ];

    /**
     * Get the column name for the "remember me" token.
     *
     * @return string
     */
    public function getRememberTokenName()
    {
        return 'token';
    }

    /**
     * 获取会储存到 jwt 声明中的标识
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * 返回包含要添加到 jwt 声明中的自定义键值对数组
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return ['role' => 'admin'];
    }

    /**
     * 性别转换
     * @return string
     */
    public function getSexAttribute()
    {
        return (string)$this->attributes['sex'];
    }

    /**
     * 状态转换
     * @return string
     */
    public function getStateAttribute()
    {
        return (string)$this->attributes['state'];
    }


    /**
     * 开启google验证器
     * @return string
     */
    public function getIsGoogleAuthAttribute()
    {
        return (string)$this->attributes['is_google_auth'];
    }

    /**
     * 通过用户检查权限
     * @param $id
     * @param $method
     * @param $route
     * @return bool
     */
    public function checkPermission($id,$method,$route)
    {
        $role_model=new SysRole();
        $roles=$role_model->getRolesFromCache($id);
        if(empty($roles)) return false;

        $permissions_array=$allow_permissions= [];

        foreach ($roles as $value) {
            $permission_model=new SysPermission();
            list($node,$permissions) = $permission_model->getPermissions($value);
            $permissions_array=array_merge($permissions_array,$permissions);
        }

        foreach($permissions_array as $row){
            $allow_permissions[]=$row[1];
        }
        if(in_array($route,$allow_permissions)){
            return true;
        }
        return false;
    }
}
